package cn.com.jbs.course.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.jbs.cloudservice.conf.Config;
import cn.com.jbs.course.message.resp.Article;

public class MySqlManger {
	private static Logger log = LoggerFactory.getLogger(MySqlManger.class);
	/** 连接数据库所需要的五要素（可从数据库详情页中查到相应信息） *****/
	static String databaseName = Config.MYSQLNAME;
	static String host = Config.MYSQLHOST;
	static String port = Config.MYSQLPORT;
	static String driverName = "com.mysql.jdbc.Driver";
	static String dbUrl = "jdbc:mysql://";
	static String serverName = host + ":" + port + "/";
	static String connName = dbUrl + serverName + databaseName;

	/****** 接着连接并选择数据库名为databaseName的服务器 ******/
	static {
		
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			log.error("Class.forName", e);
		}
	}

	public static List<Article> getArtList(String id) {

		log.debug("begin getArticle.....");
		Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = null;
		List<Article> list =new ArrayList<Article>();
		try {
			 connection = DriverManager.getConnection(connName, Config.USER,
					Config.PWD);
			stmt = connection.createStatement();
			/* 至此连接已完全建立，就可对当前数据库进行相应的操作了 */

			// 检索数据
			sql = "select ID,MSG,TITLE,DESCRIPTION,PICURL,URL from CONTENTMSG where ID='"+id+"'";
			rs = stmt.executeQuery(sql);
			
			if(rs.wasNull())
				return list;
			
			while (rs.next()) {
				Article article = new Article(rs.getString("TITLE"),
						rs.getString("DESCRIPTION"), rs.getString("PICURL"),
						rs.getString("URL"));
				list.add(article);
			}
		} catch (Exception e) {
			log.error("getArticle error....", e);
		} finally {
			try {
				if (null != stmt) {
					stmt.close();
					connection.close();
				}
			} catch (SQLException e) {
				log.error("close conn error....", e);
			}

			log.debug("getArticle ok....");
		}
		return list;

	}
}
